

package com.amazonaws.demo;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.amazonaws.demo.sdb.SimpleDB;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
/**
 * This demo shows how GMS Location can be used to check for changes to the users location.  The
 * "My Location" button uses GMS Location to set the blue dot representing the users location. To
 * track changes to the users location on the map, we request updates from the
 * {@link LocationClient}.

 */

/*
 * AWS Database structure
 * every user is a domain
 */

/**
 * This shows how to create a simple activity with a map and a marker on the map.
 * <p>
 * Notice how we deal with the possibility that the Google Play services APK is not
 * installed/enabled/updated on a user's device.
 */
public class map extends FragmentActivity
implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener ,OnMarkerClickListener{
	public static AmazonClientManager clientManager = null;
	private GoogleMap mMap;
	private LocationClient mLocationClient;
	private Context context;
	private Thread autoUpdateLocation;
	//THE PHONE NUMBER OF USER
	private String userDomainName;
	//FOR AWS COMMUNICATION
	private static String lattitude;
	private static String longtitude;
	private static String nickName;
	private static String startHour;
	private static String endHour;
	private static String startMin;
	private static String endMin;
	private static String range;
	private static String status;	
	//HANDLER VARIABLES
	public Handler myHandler;
	public final int UPDATE_REQUEST = 1;
	public final int ADD_MARKER = 2;
	public final int UPDATE_USER_INFO = 3;
	public final int SEARCH_FRIEND = 4;
	public final int LIST_FRIEND = 5;
	public final int ACCEPT_FRIEND = 6;
	public final int IGNORE_FRIEND = 7;
	public final int ADD_LISTENER = 8;
	public Looper myLooper;
	//TAB 1
	public String interestedPerson;
	//TAB2
	private Button friendRequest;
	private Button addFriend;
	private TabSpec specs2;
	private AlertDialog dialog;
	private String searchPhoneNumber;
	private EditText searchPhoneNumberEdit;
	private List<String> allDomainNames;
	private ArrayList<String> friendRequestList;
	private ListView content;
	private TextView friendRequestNumberTextView;
	private ListAdapter adapter;
	private ArrayAdapter<String> mAdapter;
	AlertDialog.Builder friendRequestDialog;
	//TAB 3
	private TextView userInputStartTime;
	private TextView userInputEndTime;
	private Button update;
	private EditText EditedNickName;
	private Spinner WalkOrCar;
	private EditText UserSaySth;




	// These settings are the same as the settings for the map. They will in fact give you updates at
	// the maximal rates currently possible.
	private static final LocationRequest REQUEST = LocationRequest.create()
			.setInterval(5000)         // 5 seconds
			.setFastestInterval(16)    // 16ms = 60fps
			.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		userDomainName = getIntent().getExtras().getString("userName");
		friendRequest = (Button)findViewById(R.id.friendRequest);

		context = this;
		setUpMapIfNeeded();
		setUpLocationClientIfNeeded();
		if(!mLocationClient.isConnected()){
			mLocationClient.connect();
		}
		autoUpdateLocation();
		fetchInfoFromAWS(userDomainName);
		setUpTabFramework();
		setUpTabOne();
		setUpTabTwo();
		setUpTabThree();
		//set up the handler
		myHandler = new Handler(){
			public void handleMessage(Message msg){
				// get the data from other thread
				switch(msg.what){
				case UPDATE_REQUEST:
					lattitude = msg.getData().getString("lat");
					longtitude = msg.getData().getString("long");
					nickName = msg.getData().getString("nickName");
					startHour = msg.getData().getString("startHour");
					endHour = msg.getData().getString("endHour");
					startMin = msg.getData().getString("startMin");
					endMin = msg.getData().getString("endMin");
					range = msg.getData().getString("range");
					status = msg.getData().getString("saySth");
					break;
				case ADD_MARKER:
					mMap.addMarker(new MarkerOptions()
					.position(new LatLng(Double.parseDouble(msg.getData().getString("lattitude")), 
							Double.parseDouble(msg.getData().getString("longtitude")))).title(msg.getData().getString("friendDomainName"))
							.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_me1))
							);
					break;
				case UPDATE_USER_INFO:

					break;
				case SEARCH_FRIEND:
					searchFriend(searchPhoneNumber);
					break;
				case LIST_FRIEND:
					friendRequestList = msg.getData().getStringArrayList("friendRequestList");
					Log.d("friendRequest", friendRequest.toString());
					Log.d("friendRequestlIST", friendRequestList.toString());

					friendRequest.setText("you have " + friendRequestList.size() + " request");
					break;
				case ACCEPT_FRIEND:
					final String number = msg.getData().getString("friendNumber");
					friendRequestList.remove(friendRequestList.indexOf(number));
					Thread thread = new Thread(new Runnable(){
						public void run(){
							SimpleDB.deleteItemAttribute(userDomainName, "receivedFriendRequestItem",number);
							SimpleDB.createAttributeForItem(userDomainName, "friendListItem", number, "");
							HashMap<String,String> targetRequestList = SimpleDB.getAttributesForItem(userDomainName, "receivedFriendRequestItem");
							Set<String> allFriendRequest = targetRequestList.keySet();
							ArrayList<String> allFriendRequestList = new ArrayList<String>();
							allFriendRequestList.addAll(allFriendRequest);
							Message msg = myHandler.obtainMessage(LIST_FRIEND) ;
							Bundle bundle = new Bundle();
							bundle.putStringArrayList("friendRequestList", allFriendRequestList);
							//		Log.d("caonierdaye", allFriendRequestList.get(0));
							msg.setData(bundle);
							myHandler.sendMessage(msg);
							friendRequestDialog = new AlertDialog.Builder(context);	
							friendRequestDialog.setTitle("Friend request");
							//String[] mData = (String[]) friendRequestList.toArray();
							final ArrayAdapter<String> mmAdapter = new ArrayAdapter<String>(context,
									R.layout.list_friend_item, R.id.friendRequestNumber, friendRequestList);
							runOnUiThread(new Runnable(){
								public void run(){
									mmAdapter.notifyDataSetChanged();
									content.setAdapter(mmAdapter);
								}
							});	
  


						}
					});
					thread.start();
					break;
				case IGNORE_FRIEND:
					Log.d("hadhifgweifkf", "the ignore request is received");
					final String ignoreNumber = msg.getData().getString("friendNumber");
					friendRequestList.remove(friendRequestList.indexOf(ignoreNumber));
					Thread threadIgnore = new Thread(new Runnable(){
						public void run(){
							SimpleDB.deleteItemAttribute(userDomainName, "receivedFriendRequestItem",ignoreNumber);
							HashMap<String,String> targetRequestList = SimpleDB.getAttributesForItem(userDomainName, "receivedFriendRequestItem");
							Set<String> allFriendRequest = targetRequestList.keySet();
							ArrayList<String> allFriendRequestList = new ArrayList<String>();
							allFriendRequestList.addAll(allFriendRequest);
							Message msg = myHandler.obtainMessage(LIST_FRIEND) ;
							Bundle bundle = new Bundle();
							bundle.putStringArrayList("friendRequestList", allFriendRequestList);
							//		Log.d("caonierdaye", allFriendRequestList.get(0));
							msg.setData(bundle);
							myHandler.sendMessage(msg);
							final ArrayAdapter<String> mmAdapter = new ArrayAdapter<String>(context,
									R.layout.list_friend_item, R.id.friendRequestNumber, friendRequestList);
							runOnUiThread(new Runnable(){
								public void run(){
									mmAdapter.notifyDataSetChanged();
									content.setAdapter(mmAdapter);
								}
							});	
  
						}
					});
					threadIgnore.start();
					break;
				case ADD_LISTENER:

				}


			}
		};
	}

	@Override
	protected void onResume() {
		super.onResume();
		setUpMapIfNeeded();
		setUpLocationClientIfNeeded();
		if(!mLocationClient.isConnected()){
			mLocationClient.connect();
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mLocationClient != null) {
			mLocationClient.disconnect();
		}
	}

	private void setUpMapIfNeeded() {
		//setupDatabase();
		// Do a null check to confirm that we have not already instantiated the map.
		if (mMap == null) {
			// Try to obtain the map from the SupportMapFragment.
			mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
					.getMap();
			if (mMap != null) {
				mMap.setMyLocationEnabled(true);
			}
		}
	}

	private void setUpLocationClientIfNeeded() {
		if (mLocationClient == null) {
			mLocationClient = new LocationClient(
					getApplicationContext(),
					this,  // ConnectionCallbacks
					this); // OnConnectionFailedListener
		}
	}
	public void fecthInfoFromPreference(){
		SharedPreferences prefs = this.getSharedPreferences(
				"com.amazonaws.demo", Context.MODE_PRIVATE);

		nickName = prefs.getString("editedNickName", "sb");
		startHour =  prefs.getString("startHour", "00");
		endHour =  prefs.getString("endHour","00");
		startMin = prefs.getString("startMin","00");
		endMin = prefs.getString("endMin", "00");
		range = prefs.getString("range","I do not give a shit");
		status = prefs.getString("status","lalalala");

	}

	public void fetchInfoFromAWS(final String domainNmae){
		Thread thread = new Thread(new Runnable(){
			public void run(){
				//get info from AWS
				String lattitude = SimpleDB.getSingleAttributesForItem(domainNmae, "locationItem", "lat");
				String longtitude = SimpleDB.getSingleAttributesForItem(domainNmae, "locationItem", "long");
				String nickName = SimpleDB.getSingleAttributesForItem(domainNmae, "nickNameItem", "userNickname");
				String startHour = SimpleDB.getSingleAttributesForItem(domainNmae, "timeItem", "startHour");
				String endHour = SimpleDB.getSingleAttributesForItem(domainNmae, "timeItem", "endHour");
				String startMin = SimpleDB.getSingleAttributesForItem(domainNmae, "timeItem", "startMin");
				String endMin = SimpleDB.getSingleAttributesForItem(domainNmae, "timeItem", "endMin");
				String range = SimpleDB.getSingleAttributesForItem(domainNmae, "rangeItem", "range");
				String saySth = SimpleDB.getSingleAttributesForItem(domainNmae, "saySthItem", "status");
				//send message
				Message msg = myHandler.obtainMessage(UPDATE_REQUEST) ;
				Bundle bundle = new Bundle();
				bundle.putString("lat", lattitude);
				bundle.putString("long", longtitude);	
				bundle.putString("nickName", nickName);	
				bundle.putString("startHour", startHour);
				bundle.putString("endHour", endHour);	
				bundle.putString("startMin", startMin);	
				bundle.putString("endMin", endMin);	
				bundle.putString("range", range);	
				bundle.putString("saySth", saySth);	

				//bundle.putString("nickNameItem",SimpleDB.getSingleAttributesForItem("wuyueLocation", "nickNameItem", "userNickname"));
				msg.setData(bundle);
				myHandler.sendMessage(msg);

			}
		});
		thread.start();
	}
	/**
	 * Implementation of {@link LocationListener}.
	 */
	@Override
	public void onLocationChanged(Location location) {
	}


	@Override
	public void onConnected(Bundle connectionHint) {
		if (autoUpdateLocation.isAlive()){
			autoUpdateLocation.start();
		}
		mLocationClient.requestLocationUpdates(
				REQUEST,
				this);  // LocationListener
		//auto-zoom in
		mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLocationClient.getLastLocation().getLatitude(), 
				mLocationClient.getLastLocation().getLongitude()), 15.0f));
	}

	/**
	 * Callback called when disconnected from GCore. Implementation of {@link ConnectionCallbacks}.
	 */
	@Override
	public void onDisconnected() {
		// Do nothing
	}

	/**
	 * Implementation of {@link OnConnectionFailedListener}.
	 */
	@Override
	public void onConnectionFailed(ConnectionResult result) {
		// Do nothing
	}

	//Create a new item in a domain
	private class CreateDomainTask extends AsyncTask<Void, Void, Void> {

		protected Void doInBackground(Void... voids) {

			try {
				SimpleDB.createDomain("wuyueLocation");
			} catch (Throwable e) {
				throw new IllegalArgumentException();
			}

			return null;
		}

		protected void onPostExecute(Void result) {
			finish();
		}
	}


	// Create a item in a domain
	private class CreateItemTask extends AsyncTask<Void, Void, Void> {

		protected Void doInBackground(Void... voids) {

			try {
				SimpleDB.createItem("wuyueLocation",
						mLocationClient.getLastLocation().getLatitude() +"");				
				SimpleDB.createItem("wuyueLocation",
						mLocationClient.getLastLocation().getLongitude() +"");
			} catch (Throwable e) {
				throw new IllegalArgumentException();
			}

			return null;
		}

		protected void onPostExecute(Void result) {
			finish();
		}
	}


	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	// userDomainName
	// locationItem////// nickNameItem /////timeItem   ////rangeItem ///saySthItem
	public void setupDatabase(){
		//SimpleDB.createAttributeForItem( "wuyueLocation", "location", "lat",mLocationClient.getLastLocation().getLatitude() + "");
		//SimpleDB.createAttributeForItem( "wuyueLocation", "location", "long",mLocationClient.getLastLocation().getLongitude() + "");

		SimpleDB.createDomain( userDomainName );
		SimpleDB.createItem( userDomainName, "locationItem"); 
		//		HashMap<String, String> myLocation = new HashMap<String,String>();
		//		myLocation.put("lat", mLocationClient.getLastLocation().getLatitude() + "");
		//		myLocation.put("long", mLocationClient.getLastLocation().getLongitude() + "");
		//		SimpleDB.updateAttributesForItem(logInName, "locationItem", myLocation);
		//create user's Nickname
		SimpleDB.createItem(userDomainName,"nickNameItem");
		//		HashMap<String, String> userNickname = new HashMap<String,String>();
		//		userNickname.put("userNickname", "hjqturtle");
		//		SimpleDB.updateAttributesForItem(logInName, "nickNameItem", userNickname);
		//create time item
		SimpleDB.createItem(userDomainName,"timeItem");
		//		HashMap<String, String> myTime = new HashMap<String,String>();
		//		myTime.put("startHour", "3");
		//		myTime.put("endHour", "6");
		//		myTime.put("startMin", "30");
		//		myTime.put("endMin", "50");
		//		SimpleDB.updateAttributesForItem(logInName, "timeItem", myTime);
		//create range item
		SimpleDB.createItem(userDomainName,"rangeItem");
		//		HashMap<String, String> myRange = new HashMap<String,String>();
		//		myRange.put("range", "walk");
		//		SimpleDB.updateAttributesForItem(logInName, "rangeItem", myRange);
		//create say something
		SimpleDB.createItem(userDomainName,"saySthItem");
		//		HashMap<String, String> mysaySth = new HashMap<String,String>();
		//		mysaySth.put("status", "zou zou zou chi fan qu !!!");
		//		SimpleDB.updateAttributesForItem(logInName, "saySthItem", mysaySth);
	}

	public void autoUpdateLocation(){
		autoUpdateLocation = new Thread(new Runnable(){
			public void run(){
				try {

					if(!SimpleDB.getDomainNames().contains(userDomainName)){
						setupDatabase();
					}
					while (true && mLocationClient.isConnected()) {
						//getFriendRequest();

						HashMap<String, String> myLocation = new HashMap<String,String>();
						myLocation.put("lat", mLocationClient.getLastLocation().getLatitude() + 1.0 +"");
						myLocation.put("long", mLocationClient.getLastLocation().getLongitude() + "");
						SimpleDB.updateAttributesForItem(userDomainName, "locationItem", myLocation);

						HashMap<String, String> location = SimpleDB.getAttributesForItem(userDomainName, "locationItem");
						final String  lattitude = location.get("lat");
						String longtitude = location.get("long");

						runOnUiThread(new Runnable(){
							public void run(){
								SharedPreferences settings = getSharedPreferences("preference", 0);

								Toast.makeText(getApplicationContext(), "LAT IS " + lattitude, 
										Toast.LENGTH_SHORT).show();
							}
						});	
						Thread.sleep(3000);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}

	public void setUpTabFramework(){
		TabHost th = (TabHost) findViewById(R.id.tabhost);
		th.setup();
		TabSpec specs = th.newTabSpec("tag1");
		specs.setContent(R.id.tab1);
		specs.setIndicator("Map");
		th.addTab(specs);
		specs2 = th.newTabSpec("tag2");
		specs2.setContent(R.id.tab2);
		specs2.setIndicator("Friend List");
		th.addTab(specs2);
		specs = th.newTabSpec("tag3");
		specs.setContent(R.id.tab3);
		specs.setIndicator("Setting");
		th.addTab(specs);
		th.setOnTabChangedListener(new OnTabChangeListener(){
			@Override
			public void onTabChanged(String tabId) {
				if(tabId == "tag3"){
					fecthInfoFromPreference();
					EditedNickName.setText(nickName);
					userInputStartTime.setText(startHour + ":" + startMin);
					userInputEndTime.setText(endHour + ":" + endMin);
					if (range == "I do not give a shit"){
						WalkOrCar.setSelection(0);
					}else if(range == "I can drive my 28 big dunky"){
						WalkOrCar.setSelection(1);
					}else{
						WalkOrCar.setSelection(2);
					}
					UserSaySth.setText(status);
				}else if(tabId == "tag2"){
					Thread thread = new Thread(new Runnable(){
						public void run(){
							HashMap<String,String> targetRequestList = SimpleDB.getAttributesForItem(userDomainName, "receivedFriendRequestItem");
							Set<String> allFriendRequest = targetRequestList.keySet();
							ArrayList<String> allFriendRequestList = new ArrayList<String>();
							allFriendRequestList.addAll(allFriendRequest);
							Message msg = myHandler.obtainMessage(LIST_FRIEND) ;
							Bundle bundle = new Bundle();
							bundle.putStringArrayList("friendRequestList", allFriendRequestList);
							//		Log.d("caonierdaye", allFriendRequestList.get(0));
							msg.setData(bundle);
							myHandler.sendMessage(msg);
						}
					});
					thread.start();
				}
			}});


	}

	public void setUpTabOne(){
		//~~~~~~~~~~~~~~~~NEED TO BE DONE FOR EVERY FRIEND
		//NEED TO BE CHANGED!
		//Get a list of domain names from friend list and create marker for each one of them
		//Set the title of marker as the domain name(phone number)
		//Use the title of marker to load information from AWS to the dialog
		final String friendDomainName = "wuyueLocation";
		Thread thread = new Thread(new Runnable(){
			public void run(){
				//Log.d("fafafsdgdgvdsgbdrfgbdzd", "")
				lattitude = SimpleDB.getSingleAttributesForItem(friendDomainName, "locationItem", "lat");
				longtitude = SimpleDB.getSingleAttributesForItem(friendDomainName, "locationItem", "long");
				Message msg = myHandler.obtainMessage(ADD_MARKER) ;
				Bundle bundle = new Bundle();

				bundle.putString("friendDomainName", friendDomainName);
				bundle.putString("lattitude", lattitude);
				bundle.putString("longtitude", longtitude);
				msg.setData(bundle);
				myHandler.sendMessage(msg);

				Log.d("fafafsdgdgvdsgbdrfgbdzd", ""+ lattitude);
			}
		});
		thread.start();

		Log.d("hengjiaqi131234534412", ""+ lattitude);
		//mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(lattitude), 
		//	Double.parseDouble(longtitude))).title(friendDomainName));

		//~~~~~~~~~~~~~~~~
		//fetchInfoFromAWS(userDomainName);
		mMap.setOnMarkerClickListener(new OnMarkerClickListener()
		{
			public boolean onMarkerClick(Marker marker) {

				//TO BE CHANGED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
				//fetchInfoFromAWS(userDomainName);
				AlertDialog.Builder builder = new AlertDialog.Builder(context);	
				builder.setTitle(nickName)
				.setPositiveButton("Text", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

					}
				})
				.setNegativeButton("Call", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

					}
				});
				LayoutInflater inflater = getLayoutInflater();

				LinearLayout content = (LinearLayout) inflater.inflate(R.layout.dialog_layout, null);
				TextView time = (TextView) inflater.inflate(R.layout.dialog_time, null);

				//check to see if the data are null
				if(startHour == null){

				}
				time.setText(startHour + ":" + startMin + " to " + endHour +  ":" +endMin);

				content.addView(time);

				TextView walkOrCar = (TextView) inflater.inflate(R.layout.dialog_range, null);
				walkOrCar.setText(range);
				content.addView(walkOrCar);

				TextView statusUser = (TextView) inflater.inflate(R.layout.dialog_status, null);
				statusUser.setText(status);
				content.addView(statusUser);

				builder.setView(content);

				interestedPerson = marker.getTitle();
				AlertDialog dialog = builder.create();
				dialog.setContentView(R.layout.dialog_layout);

				Toast.makeText(getApplicationContext(), "" +marker.getTitle(), Toast.LENGTH_SHORT).show();
				builder.show();
				return true;
			}
		}); 
	}

	public void setUpTabTwo(){

		addFriend = (Button)findViewById(R.id.addFriend);

		friendRequestNumberTextView = (TextView)findViewById(R.id.friendRequestNumber);
		addFriend.setOnClickListener(
				new OnClickListener() {
					public void onClick(View v) {
						LayoutInflater inflater = getLayoutInflater();
						LinearLayout content = (LinearLayout) inflater.inflate(R.layout.addfriend_layout, null);
						AlertDialog.Builder builder = new AlertDialog.Builder(context);	
						builder.setTitle("Add Friend");
						dialog = builder.create();
						//View v1 = inflater.inflate(R.layout.addfriend_layout, null);
						final Button searchFriend1 = (Button)content.findViewById(R.id.searchFriend1);
						final Button cancelButtonInAddFriend = (Button)content.findViewById(R.id.cancelButtonInAddFriend);
						builder.setView(content);
						dialog.setContentView(R.layout.addfriend_layout);

						searchPhoneNumberEdit = (EditText)content.findViewById(R.id.searchPhoneNumber);

						Log.d("cao ni mei 2123132", searchPhoneNumberEdit.getText().toString() + "");
						Log.d("cao ni mei searchFriend ", searchPhoneNumberEdit.getText().toString() + "");
						cancelButtonInAddFriend.setOnClickListener(
								new OnClickListener() {
									public void onClick(View v) {	
										finish();
									}
								}
								);	
						searchFriend1.setOnClickListener(
								new OnClickListener() {
									public void onClick(View v) {	
										searchPhoneNumber = searchPhoneNumberEdit.getText().toString();
										if(searchPhoneNumber.equals("")){
											Toast.makeText(getApplicationContext(), "Please enter a phone number!", Toast.LENGTH_SHORT).show();
										}else{
											Thread thread = new Thread(new Runnable(){
												public void run(){
													allDomainNames =  SimpleDB.getDomainNames();
													Message msg = myHandler.obtainMessage(SEARCH_FRIEND) ;
													myHandler.sendMessage(msg);
												}
											});
											thread.start();
										}
									}
								}
								);	

						builder.show();
					}
				}
				);
		friendRequest.setOnClickListener(
				new OnClickListener() {
					public void onClick(View v) {
						LayoutInflater inflater = getLayoutInflater();
						content = (ListView) inflater.inflate(R.layout.friend_request_list_view, null);
						LinearLayout row = (LinearLayout) inflater.inflate(R.layout.list_friend_item, content, false);
						friendRequestDialog = new AlertDialog.Builder(context);	
						friendRequestDialog.setTitle("Friend request");
						//String[] mData = (String[]) friendRequestList.toArray();
						runOnUiThread(new Runnable(){
							public void run(){
								mAdapter = new ArrayAdapter<String>(context,
										R.layout.list_friend_item, R.id.friendRequestNumber, friendRequestList);
							}
						});	



						content.setOnItemClickListener(new AdapterView.OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent, final View view,
									int position, long id) {
								friendRequestNumberTextView = (TextView)view.findViewById(R.id.friendRequestNumber);
								final String number = friendRequestNumberTextView.getText().toString();
								Log.d("Tapped the number" ,  number);

								AlertDialog.Builder builder = new AlertDialog.Builder(context);
								builder.setMessage("Accept or Ignore request")
								.setNegativeButton("Accept", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int id) {
										Log.d("hadhifgweifkf", "acceptButton is ~~~~~~" + friendRequestNumberTextView);
										//String number = friendRequestNumberTextView.getText().toString();
										Message msg = myHandler.obtainMessage(ACCEPT_FRIEND) ;
										Bundle bundle = new Bundle();
										bundle.putString("friendNumber", number);
										msg.setData(bundle);
										myHandler.sendMessage(msg);
										//content.setOnItemClickListener(null);
										
									}
								})
								.setPositiveButton("Ignore", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int id) {
										//String number = friendRequestNumberTextView.getText().toString();
										Message msg = myHandler.obtainMessage(IGNORE_FRIEND);
										Bundle bundle = new Bundle();
										bundle.putString("friendNumber", number);
										msg.setData(bundle);
										myHandler.sendMessage(msg);
										//content.setOnItemClickListener(null);
									}
								});
								// Create the AlertDialog object and return it
								builder.create();
								builder.show();

							}
						});


						content.setAdapter(mAdapter);
						//row.setTag(holder);
						dialog = friendRequestDialog.create();
						friendRequestDialog.setView(content);
						friendRequestDialog.show();
						//
					}
				}
				);


	}

	public void setUpTabThree() {
		EditedNickName = (EditText)findViewById(R.id.userNickName);
		UserSaySth = (EditText)findViewById(R.id.userSaySomething);
		WalkOrCar = (Spinner)findViewById(R.id.rangeSpinner);
		userInputStartTime = (TextView) findViewById(R.id.startTime);
		userInputEndTime = (TextView) findViewById(R.id.endTime);
		update = (Button)this.findViewById(R.id.updateUserButton);
		update.setOnClickListener(
				new OnClickListener(){
					public void onClick(View v){

						Thread thread = new Thread(new Runnable(){
							public void run(){
								HashMap<String, String> userNickname = new HashMap<String,String>();
								userNickname.put("userNickname", EditedNickName.getText().toString());
								Log.d("user input is...." ,  EditedNickName.getText().toString());
								SimpleDB.updateAttributesForItem(userDomainName, "nickNameItem", userNickname);	
								HashMap<String, String> myTime = new HashMap<String,String>();
								Log.d("user input is...." ,  userInputStartTime.getText().toString());
								Log.d("user input is...." ,  userInputEndTime.getText().toString());

								myTime.put("startHour", userInputStartTime.getText().toString().split(":")[0]);
								myTime.put("endHour", userInputEndTime.getText().toString().split(":")[0]);
								myTime.put("startMin", userInputStartTime.getText().toString().split(":")[1]);
								myTime.put("endMin", userInputEndTime.getText().toString().split(":")[1]);
								SimpleDB.updateAttributesForItem(userDomainName, "timeItem", myTime);
								//create range item
								HashMap<String, String> myRange = new HashMap<String,String>();
								myRange.put("range", WalkOrCar.getSelectedItem().toString());
								SimpleDB.updateAttributesForItem(userDomainName, "rangeItem", myRange);
								//create say something
								HashMap<String, String> mysaySth = new HashMap<String,String>();
								mysaySth.put("status", UserSaySth.getText().toString());
								SimpleDB.updateAttributesForItem(userDomainName, "saySthItem", mysaySth);

								SharedPreferences prefs = getSharedPreferences(
										"com.amazonaws.demo", Context.MODE_PRIVATE);
								prefs.edit().putString("editedNickName", EditedNickName.getText().toString()).commit();
								prefs.edit().putString("startHour", userInputStartTime.getText().toString().split(":")[0]).commit();
								prefs.edit().putString("endHour", userInputEndTime.getText().toString().split(":")[0]).commit();
								prefs.edit().putString("startMin", userInputStartTime.getText().toString().split(":")[1]).commit();
								prefs.edit().putString("endMin", userInputEndTime.getText().toString().split(":")[1]).commit();
								prefs.edit().putString("range", WalkOrCar.getSelectedItem().toString()).commit();
								prefs.edit().putString("status", UserSaySth.getText().toString()).commit();
							}
						});
						thread.start();
					}
				}
				);
		userInputStartTime.setOnClickListener(
				new OnClickListener() {
					public void onClick(View v) {
						DialogFragment newFragment = new TimePickerFragment(true);
						newFragment.show(getSupportFragmentManager(), "timePicker");		    
					}
				}
				);

		userInputEndTime.setOnClickListener(
				new OnClickListener() {
					public void onClick(View v) {
						DialogFragment newFragment1 = new TimePickerFragment(false);
						newFragment1.show(getSupportFragmentManager(), "timePicker");
					}
				}
				);

	}

	/**
	 * Button to get current Location. This demonstrates how to get the current Location as required,
	 * without needing to register a LocationListener.
	 */
	public void showMyLocation(View view) {

		if (mLocationClient != null && mLocationClient.isConnected()) {
			String msg = "Location = " + mLocationClient.getLastLocation();
			Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
			Thread thread = new Thread(new Runnable(){
				public void run(){
					SimpleDB.deleteAllItem("jiaqiLocation");
					//setupDatabase();
					HashMap<String, String> location = SimpleDB.getAttributesForItem(userDomainName, "locationItem");
					String lattitude = location.get("lat");
					String longtitude = location.get("long");
					Message msg = myHandler.obtainMessage(UPDATE_REQUEST) ;
					Bundle bundle = new Bundle();
					Log.d("zzzzzzzzzzzz", lattitude);
					bundle.putString("lat", lattitude);
					bundle.putString("long", longtitude);	
					//bundle.putString("nickNameItem",SimpleDB.getSingleAttributesForItem("wuyueLocation", "nickNameItem", "userNickname"));
					msg.setData(bundle);
					//myHandler.sendMessage(msg);
				}
			});
			thread.start();
		}
	}

	@SuppressLint("ValidFragment")

	public void searchFriend(final String phone){

		if(allDomainNames.contains(phone)){
			//HashMap<String,String> targetRequestList = SimpleDB.getAttributesForItem(phone, "receivedFriendRequestItem");
			AlertDialog.Builder builder = new AlertDialog.Builder(context);	
			builder.setTitle("Add Friend");
			final AlertDialog dialog = builder.create();
			LayoutInflater inflater = getLayoutInflater();
			LinearLayout content = (LinearLayout) inflater.inflate(R.layout.search_result, null);
			Button sendFriendRequest = (Button)content.findViewById(R.id.sendFriendRequest);
			Button cancelButton = (Button)content.findViewById(R.id.cancelInSearchResult);

			sendFriendRequest.setOnClickListener(
					new OnClickListener() {
						public void onClick(View v) {
							Thread thread = new Thread(new Runnable(){
								public void run(){
									//put my name to target's received friend request list
									HashMap<String,String> targetRequestList = SimpleDB.getAttributesForItem(phone, "receivedFriendRequestItem");
									targetRequestList.put(userDomainName, nickName);
									SimpleDB.updateAttributesForItem(phone, "receivedFriendRequestItem", targetRequestList);
									HashMap<String,String> mySentRequestList = SimpleDB.getAttributesForItem(userDomainName, "sentFriendRequestItem");
									mySentRequestList.put(phone, "");
									SimpleDB.updateAttributesForItem(userDomainName, "sentFriendRequestItem", mySentRequestList);
								}
							});
							thread.start();
						}
					}
					);
			cancelButton.setOnClickListener(
					new OnClickListener() {
						public void onClick(View v) {
							finish();
						}
					}
					);
			builder.setView(content);
			builder.show();
		}else{
			Toast.makeText(getApplicationContext(), "Cannot find the person", Toast.LENGTH_SHORT).show();

		}
	}

	public void getFriendRequest(){
		HashMap<String, String> request = SimpleDB.getAttributesForItem(userDomainName, "receivedFriendRequestItem");
		if(request.keySet().size() >0){
			specs2.setIndicator("Friend List (+" + request.keySet().size() + ")");
			friendRequest.setText("you have "+  request.keySet().size() + " friend request");
		}else{
			friendRequest.setText("you have 0 friend request");
		}
	}


	public class TimePickerFragment extends DialogFragment
	implements TimePickerDialog.OnTimeSetListener {

		public boolean isStart;
		public TimePickerFragment(boolean isStart){
			this.isStart = isStart;
		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current time as the default values for the picker
			final Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);

			// Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(getActivity(), this, hour, minute,
					DateFormat.is24HourFormat(getActivity()));
		}

		public void onTimeSet1(TimePicker view, int hourOfDay, int minute) {
			// Do something with the time chosen by the user
			// userInputEndTime.setText(hourOfDay + " : "+ minute);
		}

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			String time;
			if(minute < 10){
				time = hourOfDay + " : "+ 0 + "" + minute;
			}else{
				time = hourOfDay + " : "+ minute;
			}

			if(isStart){
				userInputStartTime.setText(time);
			}else{
				userInputEndTime.setText(time);
			}
		}


	}

	
	
}






